(function() {

    const url = '/hello';

    const result = document.querySelector('.result');

    const xhrGetBtn = document.querySelector('.xhr-get');
    // 添加 click 事件监听器
    xhrGetBtn.addEventListener('click', evt => {

        // 1、创建 XMLHttpRequest实例
        let x = new XMLHttpRequest();
        console.log( x.readyState );

        // 2、侦听 readyState 属性值的变化
        x.onreadystatechange = function(){
            console.log( x.readyState );
            if( x.readyState === x.OPENED ) {
                console.log( '建立连接' );
                return;
            }
            if( x.readyState === x.HEADERS_RECEIVED ) {
                console.log( '已成功接收响应头' );
                console.log( x.getAllResponseHeaders() );
                return;
            }
            if( x.readyState === x.LOADING ) {
                console.log( '正在获取响应体' );
                return;
            }
            if( x.readyState === x.DONE ){
                console.log( '完毕' );
                console.log( x.response );
                console.log( x.responseText );
                console.log( x.responseXML );
                // 将响应结果显示到页面上
                result.innerHTML = x.responseText;
            }
        }

        let method = 'get';
        let queryString = '?name=阿芳';
        // 3、打开连接
        x.open( method, `${url}${queryString}` );

        // 5、发送请求
        x.send(null);

    }, false);

    const xhrPostBtn = document.querySelector('.xhr-post');
    xhrPostBtn.addEventListener('click', () => {
        // 1、创建XMLHttpRequest实例
        let $http = new XMLHttpRequest();

        // 2、侦听 readyState 属性值的变化
        $http.addEventListener('readystatechange',evt => {
            // if( $http.readyState === $http.DONE ) {
            if( evt.target.readyState === evt.target.DONE ) {
                // console.log( $http.response );
                console.log( evt.target.response );
                let x = JSON.parse( evt.target.responseText );
                console.log( x.success, x.message );
                // 将响应结果显示到页面上
                result.innerHTML = evt.target.responseText;
            }
        },false);

        // 3、打开连接
        $http.open('POST', url);

        // 4、设置请求头
        $http.setRequestHeader( 'content-type', 'application/x-www-form-urlencoded' );

        let body = 'name=阿芳';
        // 5、发送请求
        $http.send( body );
    },false);

})();